import React, { useState, useCallback, useEffect } from 'react';
import { useHistory } from 'react-router-dom';
import { List, InputItem, Button, WhiteSpace, Toast } from 'antd-mobile';
import useUserInfo from '../../models/userInfo';
import { login, userInfo } from '../../services/Login';

function checkStuID(stuID) {
  if (!/\d{12}/.test(stuID)) {
    throw new Error('请检查学号');
  }
}

const Index = () => {
  const [stuID, setStuID] = useState('');
  const [loading, setLoading] = useState(false);
  const modelUserInfo = useUserInfo();
  const history = useHistory();

  useEffect(() => {
    if (modelUserInfo.userInfo.uid && modelUserInfo.userInfo.uid !== 0) {
      history.push('/list');
    }
  }, []);

  useEffect(() => {
    if (loading) {
      Toast.loading('请稍后...');
    } else {
      Toast.hide();
    }
  }, [loading]);

  const submit = useCallback(async () => {
    setLoading(true);
    try {
      checkStuID(stuID);
      await login(stuID);
      const info = await userInfo();
      modelUserInfo.saveUserInfo(info.nk, info.pt, info.uid);
      setLoading(false);
      history.push('/list');
    } catch (e) {
      setLoading(false);
      Toast.fail(e.message, 1);
    }
  }, [stuID, modelUserInfo.saveUserInfo]);

  (async () => {
    try {
      const info = await userInfo();
      modelUserInfo.saveUserInfo(info.nk, info.pt, info.uid);
      history.push('/list');
    } catch (e) {
      console.log(e.message);
      return
    }
  })();

  return (
    <div>
      <List renderHeader={() => '请进行登录'}>
        <InputItem
          type="text"
          placeholder="输入你的学号"
          onChange={(e) => {
            setStuID(() => e);
          }}
        >
          学号
        </InputItem>
      </List>
      <WhiteSpace />
      <Button type="primary" onClick={submit}>
        登录
      </Button>
    </div>
  );
};

export default Index;
